/** 
 * @author    Grupo 06
 *   
 * @brief     Implements a ac_tlm keyboard.
 *  
 *   This library is free software; you can redistribute it and/or
 *   modify it under the terms of the GNU Lesser General Public
 *   License as published by the Free Software Foundation; either
 *   version 2.1 of the License, or (at your option) any later version.
 * 
 *   This library is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *   Lesser General Public License for more details.
 * 
 * 
 */

//////////////////////////////////////////////////////////////////////////////
// Standard includes
// SystemC includes
// ArchC includes

#include "ac_tlm_tec.h"

//////////////////////////////////////////////////////////////////////////////

/// Namespace to isolate memory from ArchC
using user::ac_tlm_tec;

/// Constructor
ac_tlm_tec::ac_tlm_tec( sc_module_name module_name , int k ) :
  sc_module( module_name ),
  target_export("iport")
{
  /// Binds target_export to the keyboard
  target_export( *this );

  posicao=0;

  for(int i=0; i<TEC_BUFFER;i++)
    buffer[i]='\0';

  //create a thread to read the keyboard
  SC_HAS_PROCESS(ac_tlm_tec);
  SC_THREAD ( ler_tec );

}

/// Destructor
ac_tlm_tec::~ac_tlm_tec() {

  //destroi

}

/** Internal Write
 * Note: Always write 32 bits
 * @param a is the address to write
 * @param d id the data being write
 * @returns A TLM response packet with SUCCESS
 */

void ac_tlm_tec::ler_tec() // fica sempre ativo, lendo o teclado e colocando no buffer....
{ 
  SDLKey temp;
  SDL_Event event; 

  while(1) {
    wait(10000,SC_NS); // Temporizador
    while(SDL_PollEvent(&event)) {// aguarda  eventos tratados por sdl
      switch( event.type ){
        case SDL_KEYDOWN: //o que nos interessa eh o tecla apertada
          temp = event.key.keysym.sym;
          buffer[posicao] = (char) temp;
          if( (posicao+1)>TEC_BUFFER) //Para que nao se exceda o tamanho do buffer
            posicao=(posicao+1)%TEC_BUFFER;	
          else
            posicao++;
          break;
      }
    }
  }
}
/** Internal Read
 * Note: Always read 32 bits
 * @param a is the address to read
 * @param d id the data that will be read
 * @returns A TLM response packet with SUCCESS and a modified d
 */
ac_tlm_rsp_status ac_tlm_tec::readt( const uint32_t &a , uint32_t &desejado )
{
  wait(10000,SC_NS);
  desejado =  buffer[a];
  for(int i = a; i < posicao; i++ ){
    buffer[i] = buffer[i + 1];
    posicao--; }
    return SUCCESS;  
}



